<?php

namespace App\Http\Middleware;

use App\Models\MedicalRecord;
use Closure;

class ValidateUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {


        $record_id = $request->input('record_id');

        $record = MedicalRecord::where('is_del', '=', 0)
            ->find($record_id);

        if (!$record) {
            abort(400, '病例不存在！');
        }

        $user_id = \Auth::user()->id;

        $type = \Auth::user()->type;
        //如果融云token为空  生成token
        if ($type == 1) {
            if ($user_id != $record->patient_id) {
                abort(400, '只能对自己的病例进行操作！');
            }
        }else{
            if ($user_id != $record->doctor_id) {
                abort(400, '只能对自己的患者病例进行操作！');
            }
        }

        return $next($request);
    }
}
